package cn.edu.zjicm.wordsnet_d.pay;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;
import cn.edu.zjicm.wordsnet_d.activity.SelectBookActivity;
import cn.edu.zjicm.wordsnet_d.data.MobclickAgentData;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.synchronize.PayInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.ServerInterface;
import cn.edu.zjicm.wordsnet_d.synchronize.UserInterface;

import com.alipay.sdk.app.PayTask;

public class Alipay {
	private final String PARTNER = "2088711894807780";
	private final String SELLER = "2088711894807780";
	private final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAM+cvR0y"
			+ "RDIsdeR5GuZ4OddEMLaZuzrQMhp3XSBc0HUojY70zTpa1xnKOIlcMQ6MR3/+MfMGd/oPHoKN2kAeS+CDB+ToIRtw5y"
			+ "DYEmD5bY1m3scD3JLMgIaCEdO07LQBoBbLNX4LvMBiO4xQ7Q8gFh++2viLQ7MM3WDvPjclNjAxAgMBAAECgYAOknnTq"
			+ "suOmgBMYRO6SYYFzgt9RZ0Wq7ZYlTg8JUeccZQ+DIC7L9UZQlBlk8r9smryWO04maOiMZ16nGpNRdMddrNN8grWCq6B0"
			+ "pW1XZ1UVKbOAfo2E2gvprZJ1n0xJO9Z5kz2dGMUKP5B7KnKFvEKnBAGG7EeL8mhBh528zfwYQJBAO5mmnn+gnG5mEuCrU"
			+ "IfhZt/e9ljXs/fQyNAHUGDLgZcdLant2qNhUtMLynWRmYA8brbgf1buQC3zmluBazG5GsCQQDe8EfoFMqN1ukZuKoueRu4"
			+ "Dau8DB8xtSC0amRD0/Ni+ObGQkT/Cj9QrcEp/7PC0BWwmH9Aez05kbcLaCzsssTTAkAuPtcOfTF+sBr74uCLKCQ50tQKin0"
			+ "048FZUDGcqL6/2yWE3Sn2UHef8KphekBzvxElRzmDFUzg98bhqscNChP7AkEAzrLjSId2Ydn/V6zChMIe9CAguQJYLcMs5n"
			+ "m6KrUp9PqnJOyugfSjTY88CE+fAKHjak+JtGRPGMBEgVv+QxtgpwJBAKOFno1DwWbWhTIffft1U8yP7+eM0tXe6MPTGko9Vx"
			+ "SFdEd3gem5LGp4+ENwXKkVy0awP0kSu/kdO1hvEAcemuU=";
	private final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFlj"
			+ "hNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilI"
			+ "ZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";

	private final int SDK_PAY_FLAG = 1;
	private final int SDK_CHECK_FLAG = 2;

	public final String NOTIFY_URL = ServerInterface.IP + ServerInterface.PORT + "/youqu/notify.htm";

	public static Order currentOrder;
	public int refreshOrderStatusCount;
	private final int DELAY[] = { 60000, 30000, 15000, 5000, 1000, 500 };

	private Context mContext;

	public Alipay(Context mContext) {
		this.mContext = mContext;
	}

	Handler getUserBoughtHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case UserInterface.MSG_START:
				break;
			case UserInterface.MSG_SUCCESS:
				Order order = WordFactory.getInstance(mContext).getOrderById(currentOrder.getOrderId());
				if (order != null && order.getTradeStatus() == 1) {
					Toast.makeText(mContext, "充值成功", Toast.LENGTH_SHORT).show();
					((Activity) mContext).finish();
				} else if (order != null && order.getTradeStatus() == 2) {
					Toast.makeText(mContext, "充值失败，请联系客服", Toast.LENGTH_SHORT).show();
					((Activity) mContext).finish();
				} else {
					if (refreshOrderStatusCount == 5) {
						Toast.makeText(mContext, "充值完成，订单正在处理中", Toast.LENGTH_SHORT).show();
						((Activity) mContext).finish();
					}
					// 充值后，如果订单仍是待处理状态，1分钟后再尝试更新订单状态，最多尝试5次
					if (refreshOrderStatusCount > 0) {
						mHandler.postDelayed(new Runnable() {
							@Override
							public void run() {
								refreshOrderStatusCount--;
								PayInterface.getInstance(mContext).getUserBought(getUserBoughtHandler);
								PayInterface.getInstance(mContext).getUserWealth();
							}
						}, DELAY[refreshOrderStatusCount]);
					}
				}

				break;
			case UserInterface.MSG_UNSUCCESS:
				Toast.makeText(mContext, "获取订单状态失败，请稍后再试", Toast.LENGTH_SHORT).show();
				((Activity) mContext).finish();
				break;
			case UserInterface.MSG_WEB_SITE_ERROR:
				Toast.makeText(mContext, "连接服务器失败，获取订单状态失败，请稍后再试", Toast.LENGTH_SHORT).show();
				((Activity) mContext).finish();
				break;
			case UserInterface.MSG_WEB_SITE_ACCESS_FAILURE:
				Toast.makeText(mContext, "请确认网络是否连接，获取订单状态失败，请稍后再试", Toast.LENGTH_SHORT).show();
				((Activity) mContext).finish();
				break;
			case UserInterface.MSG_BAD_NETWORK:
				Toast.makeText(mContext, "网络未连接，获取订单状态失败，请稍后再试", Toast.LENGTH_SHORT).show();
				((Activity) mContext).finish();
				break;
			}
		};
	};

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				Result resultObj = new Result((String) msg.obj);
				String resultStatus = resultObj.resultStatus;

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					SelectBookActivity.fromAlipay = true;
					String price = resultObj.getResultValue("total_fee");
					if (currentOrder != null && currentOrder.getOrderAmount() != Double.parseDouble(price)) { // 校验用户充值金额和规定价格是否相符
						Toast.makeText(mContext, "充值失败，充值金额与价格不符", Toast.LENGTH_SHORT).show();
						MobclickAgentData.reCharge(mContext, "充值失败，充值金额与价格不符");
					} else {
						refreshOrderStatusCount = 5;
						PayInterface.getInstance(mContext).getUserBought(getUserBoughtHandler);
						PayInterface.getInstance(mContext).getUserWealth();

						MobclickAgentData.reCharge(mContext, price + "元成功");
					}
				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”
					// 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(mContext, "充值结果确认中", Toast.LENGTH_SHORT).show();
					} else {
						WordFactory.getInstance(mContext).deleteLastOrderLog();
						Toast.makeText(mContext, "充值失败", Toast.LENGTH_SHORT).show();
					}
					MobclickAgentData.reCharge(mContext, "失败");
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(mContext, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		};
	};

	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay(String orderID, String subject, String body, String price) {
		String orderInfo = getOrderInfo(orderID, subject, body, price);
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask((Activity) mContext);
				// 调用支付接口
				String result = alipay.pay(payInfo);

				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public void check() {
		Runnable checkRunnable = new Runnable() {

			@Override
			public void run() {
				PayTask payTask = new PayTask((Activity) mContext);
				boolean isExist = payTask.checkAccountIfExist();

				Message msg = new Message();
				msg.what = SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();
	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask((Activity) mContext);
		String version = payTask.getVersion();
		Toast.makeText(mContext, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getOrderInfo(String orderID, String subject, String body, String price) {
		// 合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + orderID + "\"";
		// orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + NOTIFY_URL + "\"";

		// 接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		// orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 获取外部订单号
	 * 
	 */
	public static String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}
}
